
const path = require('path');
const Glob = require('glob');
const pify = require('pify');
const fs = require('fs');
const root = process.cwd();
const dir = path.join(root, 'src');
const createRoutes = require('./route');

const glob = pify(Glob);
class GenerateRoutesAndFiles {
  constructor() {
    this.files = {};
    this.existsFolder = false;
  }
  async generateFiles() {
    this.files = {};
    (await glob(`pages/**/*.{vue,js}`, {
      cwd: path.resolve(process.cwd(), './src'),
      ignore: ['**/*.test.*', '**/*.spec.*', '**/-*.*']
    })).forEach(f => {
      const key = f.replace(/\.(js|vue)$/, '');
      if (/\.vue$/.test(f) || !this.files[key]) {
        this.files[key] = f.replace(/('|")/g, '\\$1');
      }
    });
    return createRoutes(
      Object.values(this.files),
      dir,
      'pages'
    );
  }

  async createRouter() {
    const routes = await this.generateFiles();
    let str = `/* eslint-disable */\n`;
    routes.component.forEach(res => {
      str += `${res}\n`;
    });
    str += `export const routes = ${JSON.stringify(routes.routes, null, 2)}`
      .replace(/"component": "(\w+?)"/g, `"component": $1`)
      .replace(/"(\w+?)":/g, '$1:');
    if (!this.existsFolder) {
      fs.mkdir(path.resolve(root, './src/routes'), err => {
        if (err) {
          this.existsFolder = true;
        }
      });
    }
    fs.writeFile(path.resolve(root, './src/routes/index.js'), str, (file) => {
      console.log('');
    });
  }
}
module.exports = GenerateRoutesAndFiles;
